package parser

import (
	"GraduationProject/public/models"
	"GraduationProject/worker/neteasy_music/fetcher/static"
	"GraduationProject/worker/neteasy_music/neteasy_music_conf"
	"encoding/json"
	"regexp"
	"strconv"
)

var (
	pagesRegex    = regexp.MustCompile(`<p class[^<]*<a title="([^"]*)" href="([^"]*)" class=[^<]*</a>[^<]*</p>`)
	nextPageRegex = regexp.MustCompile(`<a href="(/discover/playlist/\?order=[^"]*)" class=[^>]*>下一页</a>`)
)

func Pages(seed models.Record, content []byte) (seeds []models.Record, records []models.Record) {
	var pageNames [][]models.Param
	subMatch := pagesRegex.FindAllStringSubmatch(string(content), -1)
	subMatchLen := len(subMatch)

	seeds, pageNames = make([]models.Record, subMatchLen), make([][]models.Param, subMatchLen)

	for i, v := range subMatch {
		// v[1] name
		// v[2] uri
		seeds[i].SeedID = seed.SeedID
		seeds[i].Url = static.EasyNetMusic + v[2]
		seeds[i].FunctionName = neteasy_music_conf.NetEasyMusicSongs

		pageNames[i] = []models.Param{
			{Key: "uri", Value: v[2]},
			{Key: "name", Value: v[1]},
		}
	}

	pageNamesBytes, _ := json.Marshal(pageNames)

	nextPage := nextPageRegex.FindAllStringSubmatch(string(content), 1)
	if len(nextPage) == 1 {
		seeds = append(seeds, models.Record{
			SeedID:       seed.SeedID,
			Url:          static.EasyNetMusic + nextPage[0][1],
			FunctionName: neteasy_music_conf.NetEasyMusicPages,
		})
	}

	uniqueKey, _ := json.Marshal(models.Param{
		Key:   "net_easy_music_pages_unique_" + strconv.Itoa(int(seed.ID)),
		Value: seed.Url,
	})

	records = []models.Record{{
		NotElastic:   true,
		SeedID:       seed.SeedID,
		Url:          seed.Url,
		FunctionName: seed.FunctionName,
		UniqueKey:    string(uniqueKey),
		Result:       string(pageNamesBytes),
		Remarks:      "discover",
	}}

	return seeds, records
}
